

brochure = {
    /*  =====================================
    =====  Create Page for the brochure =====
    ========================================= */
    create_page : function(){
        
        // On Change ".cb_pages_num."
            $("body").on("click",".create_pages",function(){
                var page_num = $(".cb_pages_num").val();
                var page_type = $(this).attr("data-type");
                var brochure_pagination = $("#brochure_pagination").html();
                var self = $(this);
                
                if (brochure_pagination != "") {
                    jConfirm( 'Creating Pages', 'Workspace Brochure has already set some pages, Are you sure do you want to create / update new page on your workspace?','', '', '', function(e){
                        if (e == true) {
                            set_page_brochure(self,page_type,page_num);
                        }
                    });
                }else{
                    set_page_brochure(self,page_type,page_num);
                }
            });
            

            $(".cb_pages_num").keypress(function(e){
                var keyCode = e.keyCode;
                if(keyCode==13){
                    $(".create_pages").click();
                }
            })
    },
    
    /*  =====================================
    =====  Add Controls on the
            selected page in a brochure =====
    ========================================= */
    add_controls : function(){
        
        // Add Controls to the workspace
            var count_ctrls = 0;
            var self = this;
            $("body").on("click",".addControl",function(){
                var object_type = $(this).attr("data-object-type");


                //notify user if does not have a brocure page
                self.blankPage();

                switch (object_type) {
                    
                    case "box":
                        var a = '<div class="controls_container" id="controls_container_' + count_ctrls + '"  data-id="' + count_ctrls + '" style="z-index:' + count_ctrls + ';padding:10px 10px 45px 10px;min-height: 130px;">'+
                            '<div class="cc-controls hide" id="cc-controls-' + count_ctrls + '">'+
                                '<i class="fa fa-cogs view_settings_controls_container tip" data-original-title="Object Configuration" style="cursor:pointer;" id="view_settings_controls_container_' + count_ctrls + '" data-id="' + count_ctrls + '"></i>'+
                                '&nbsp;&nbsp;'+
                                '<i class="fa fa-times remove_controls_container tip" data-original-title="Remove Object" style="cursor:pointer;" id="remove_controls_container_' + count_ctrls + '" data-id="' + count_ctrls + '"></i>'+
                            '</div>'+
                            '<div class="cc-objects">'+
                                '<div class="span12" style="height: 100%;"><span class="top">span12</span><div class="box"  id="box_' + count_ctrls + '" data-id="' + count_ctrls + '"></div></div>'+   
                            '</div>'+
                        '</div>';
                        break;
                    
                    case "line":
                        var a = '<div class="controls_container" id="controls_container_' + count_ctrls + '"  data-id="' + count_ctrls + '" style="z-index:' + count_ctrls + ';max-height: 30px;">'+
                            '<div class="cc-controls hide" id="cc-controls-' + count_ctrls + '">'+
                                '<i class="fa fa-cogs view_settings_controls_container tip" data-original-title="Object Configuration" style="cursor:pointer;" id="view_settings_controls_container_' + count_ctrls + '" data-id="' + count_ctrls + '"></i>'+
                                '&nbsp;&nbsp;'+
                                '<i class="fa fa-times remove_controls_container tip" data-original-title="Remove Object" style="cursor:pointer;" id="remove_controls_container_' + count_ctrls + '" data-id="' + count_ctrls + '"></i>'+
                            '</div>'+
                            '<div class="cc-objects">'+
                                '<div class="span12" style="height: 90%;"><div class="line" style="margin-top:15px;"></div></div>'+                
                            '</div>'+
                        '</div>';
                        break;
                    case "vline":
                        var a = '<div class="controls_container" id="controls_container_' + count_ctrls + '"  data-id="' + count_ctrls + '" style="z-index:' + count_ctrls + ';min-width:10px !important;max-width:12px !important;">'+
                            '<div class="cc-controls hide" id="cc-controls-' + count_ctrls + '">'+
                                '<i class="fa fa-cogs view_settings_controls_container tip" data-original-title="Object Configuration" style="cursor:pointer;" id="view_settings_controls_container_' + count_ctrls + '" data-id="' + count_ctrls + '"></i>'+
                                '&nbsp;&nbsp;'+
                                '<i class="fa fa-times remove_controls_container tip" data-original-title="Remove Object" style="cursor:pointer;" id="remove_controls_container_' + count_ctrls + '" data-id="' + count_ctrls + '"></i>'+
                            '</div>'+
                            '<div class="cc-objects">'+
                                '<div class="span12" style="height: 90%;"><div id="vLine_resize_' + count_ctrls + '" class="line" style="border-width: 50px;width:3px;"></div></div>'+                
                            '</div>'+
                        '</div>';
                        break;
                    
                    case "label":
                        var a = '<div class="controls_container" id="controls_container_' + count_ctrls + '"  data-id="' + count_ctrls + '" style="z-index:' + count_ctrls + ';max-height: 30px;">'+
                            '<div class="cc-controls hide" id="cc-controls-' + count_ctrls + '">'+
                                '<i class="fa fa-cogs view_settings_controls_container tip" data-original-title="Object Configuration" style="cursor:pointer;" id="view_settings_controls_container_' + count_ctrls + '" data-id="' + count_ctrls + '"></i>'+
                                '&nbsp;&nbsp;'+
                                '<i class="fa fa-times remove_controls_container tip" data-original-title="Remove Object" style="cursor:pointer;" id="remove_controls_container_' + count_ctrls + '" data-id="' + count_ctrls + '"></i>'+
                            '</div>'+
                            '<div class="cc-objects">'+
                                '<div class="span12" style="height: 90%;"><span class="top cc-label">Label</span></div>'+                
                            '</div>'+
                        '</div>';
                        break;
                        
                    case "image":
                        var a = '<div class="controls_container" id="controls_container_' + count_ctrls + '"  data-id="' + count_ctrls + '" style="z-index:' + count_ctrls + ';height:50px;min-width:100px;min-height:100px;">'+
                            '<div class="cc-controls hide" id="cc-controls-' + count_ctrls + '">'+
                                '<i class="fa fa-cogs view_settings_controls_container tip" data-original-title="Object Configuration" style="cursor:pointer;" id="view_settings_controls_container_' + count_ctrls + '" data-id="' + count_ctrls + '"></i>'+
                                '&nbsp;&nbsp;'+
                                '<i class="fa fa-times remove_controls_container tip" data-original-title="Remove Object" style="cursor:pointer;" id="remove_controls_container_' + count_ctrls + '" data-id="' + count_ctrls + '"></i>'+
                            '</div>'+
                            '<div class="cc-objects">'+
                                '<form method="POST" action="/ajax/brochure?action=apply_photos" id="bochure_img_upload" class="img_upload_' + count_ctrls + '" enctype="multipart/form-data">' +
                                    '<div class="span12 imgUpload_' + count_ctrls + '">' +
                                    '<input type="file" class="brochure_upload" name="img_file" data-count="' + count_ctrls + '" data-loc="imgPreview_' + count_ctrls + '"></div>'+
                                    '<div class="span12 hide" style="height: 90%;" id="show_imgPreview_' + count_ctrls + '">' +
                                    '<div style="" class="image_properties hide" id="img-properties-' + count_ctrls + '"></div>' + 
                                    '<div class="img_prop_actions hide" id="img-properties-act-' + count_ctrls + '" style="">' + 
                                        '<div class="btn-group" data-id="' + count_ctrls + '">' +
                                            '<button class="btn tip upload_brochure_img" id="upload_brochure_img" data-original-title="Appy Image"><span class="icon-check"></span></button>' +     
                                            '<button class="btn tip" id="remove_upload_brochure_img" data-original-title="Remove Image"><span class="icon-trash"></span></button>' +                                                                         
                                        '</div>' + 
                                    '</div>' +
                                    '<img src="" style="position:absolute;width:100%;height:100%;" class="imgPreview_' + count_ctrls + '"></div>'+       
                                '</form>' +
                            '</div>'+
                        '</div>';
                        break;
                    
                }
                // var append_to = $(a).attr("data-append");
                var dataID = $("div[data-append='yes']").attr("data-id");
                    
                   // if (append_to == "yes") {
                   //      alert(dataID)
                   //     $("#box_" + dataID).append(a);
                   //     $("#controls_container_" + count_ctrls).draggable({
                   //         containment     : "#box_" + dataID,
                   //         cursor          : "move",
                   //         grid            : [ 20, 20 ]
                   //     });
                   //     $("#controls_container_" + count_ctrls).resizable({
                   //         containment : "#box_" + dataID
                   //     });
                   // }else{
                   //     $(".appendControl").append(a);
                   //     $("#controls_container_" + count_ctrls).draggable({
                   //         containment     : ".appendControl",
                   //         cursor          : "move",
                   //         grid            : [ 20, 20 ]
                   //     });
                   //     $("#controls_container_" + count_ctrls).resizable({
                   //         containment : ".appendControl"
                   //     });
                   // }


                var activeBoxeCount = $(".active_controls").length;
                if(activeBoxeCount>0){
                    var dataID = $(".active_controls").attr("data-id");
                    $("#box_" + dataID).append(a)
                    $("#controls_container_" + count_ctrls).draggable({
                       containment     : "#box_" + dataID,
                       cursor          : "move",
                       //grid            : [ 20, 20 ]
                   });
                   $("#controls_container_" + count_ctrls).resizable({
                       containment : "#box_" + dataID,
                       resize : function(e,ui){
                            var data_id = $(this).attr("data-id");
                            var obj_offsetX = e.offsetX;
                            var obj_offsetY = e.offsetY;
                            var obj_clientY = $("#vLine_resize_" + data_id).parent().css("height");
                           
                            $("#vLine_resize_" + data_id).css({"border-width":obj_clientY});
                       }
                   });
                  
                }else{
                    $(".appendControl").append(a);
                    $("#controls_container_" + count_ctrls).draggable({
                        containment     : ".appendControl",
                        cursor          : "move",
                        //grid            : [ 20, 20 ]
                     });
                    $("#controls_container_" + count_ctrls).resizable({
                        containment : ".appendControl",
                        resize : function(e,ui){
                            var data_id = $(this).attr("data-id");
                            var obj_offsetX = e.offsetX;
                            var obj_offsetY = e.offsetY;
                            var obj_clientY = $("#vLine_resize_" + data_id).parent().css("height");
                           
                            $("#vLine_resize_" + data_id).css({"border-width":obj_clientY});
                          
                        }
                    });
                  
                }
                
                // Box Resizable
                //$("#box_" + count_ctrls).resizable({
                //    containment : ".controls_container"
                //});
                
                // Controls Settings
                $("body").on("click","#view_settings_controls_container_" + count_ctrls,function(){
                    //$(this).addClass("active_controls");
                });
                
                $(".tip").tooltip({container : 'body', placement: 'top', trigger: 'hover'});
                

                //activate onBeforeOnload
                self.bind_onBeforeOnload(1)
                
                
                // Upload Preview
                
                $(".brochure_upload").change(function(event){
                    var location = $(this).attr("data-loc");
                    var count = $(this).attr("data-count");
                    var input = $(event.currentTarget);
                    var file = input[0].files[0];
                    if (file.type.match("image.*")) {
                        //console.log("is an image");
                        readURL(this,"." + location);
                        
                        
                        $(".imgUpload_" + count).hide();
                        $("#show_imgPreview_" + count).show();
                    }else{
                        showNotification({
                            message: "Please choose image only.",
                            type: "error",
                            autoClose: true,
                            duration: 3
                        });
                        $(this).val("")
                    }
                });
                
                count_ctrls++;
            });
            
            // Removing Controls
            $("body").on("click",".remove_controls_container",function(){
                var dataID = $(this).attr("data-id");
                
                jConfirm( 'Removing Controls', 'Are you sure do you want to remove this?','', '', '', function(e){
                    if (e == true) {
                        $("#controls_container_" + dataID).remove();

                        var countElement = $(".controls_container").length;
                        if(countElement==0){
                            //deactivate onBeforeOnload
                            self.bind_onBeforeOnload(0)
                        }
                        
                    }
                })
                
            });
            
            // Show Properties and make objects as an active
            $("body").on("dblclick",".controls_container",function(){
                var active_control_length = $(".active_controls").length;
                
                if (active_control_length == "0") {
                   // $(this).find(".box").attr("data-append","yes");
                   $(this).addClass("active_controls");
                }else{
                   // $(".active_controls").find(".box").attr("data-append","");
                   $(".active_controls").removeClass("active_controls");
                   $(this).addClass("active_controls");
                }
            });
            
            // Remove Active Controls
            $("body").on("click",".brochure_builder",function(){
                $(".active_controls").find(".box").attr("data-append","");
                $(".active_controls").removeClass("active_controls");
                
            });
            
            // trigger apply upload
            brochure.upload_img_brochure();
    },
    
    upload_img_brochure : function(){
        var self = this;
        
        $("body").on("click","#upload_brochure_img",function(e){
            //e.preventDefault();
            var dataID = $(this).parent().attr("data-id");
            
            $('.img_upload_' + dataID).ajaxForm(function(e) { 
                var data = JSON.parse(e);
                var noti = data['notification'];
                var img_name = data['img_name'];
                if (noti == "ok") {
                    showNotification({
                        message: data['msg'],
                        type: "success",
                        autoClose: true,
                        duration: 3
                    });
                    $(".imgPreview_" + dataID).attr("src",img_name);
                    $("#upload_brochure_img").attr("disabled",true);
                }
            });
        })
        
        $("body").on("click","#remove_upload_brochure_img",function(e){
            e.preventDefault();
            var dataID = $(this).parent().attr("data-id");
            
            jConfirm( 'Delete Image', 'Are you sure you want to remove this?','', '', '', function(e){
                if (e == true) {
                    $(".imgPreview_" + dataID).attr("src","");
                    $("#show_imgPreview_" + dataID).css({display: 'none'});
                    $(".imgUpload_" + dataID).show();
                    $('input[data-loc="imgPreview_' + dataID + '"]').val(null)
                }
            })
            
                    
                
        })
        
        
    },
    
    /*  =====================================
    =====  Save Brochure to the database ====
    ========================================= */
    
    save_brochure : function(){
        var self = this;
        $("body").on("click",".saveBrochure",function(){
            var brochure_builder = $(".brochure_builder").html();
            
            if (brochure_builder == "") {
                $(".cb_pages_num").addClass("red_validation");
                notify_e('Error', 'Need to enter number of pages in Brochure Settings.');
                fields_validation(".red_validation","red_validation");
            }else{
                var vEmptyWorkspace = $(".brochure").filter(function(){
                    return $.trim($(this).html()) == '';
                }).length;
                
                if ( vEmptyWorkspace != 0) {
                    jConfirm( 'Brochure Saving', 'Other pages is empty, Are you sure do you want to proceed?','', '', '', function(e){
                        if (e == true) {
                            save_workspace_functions("#cBrochure_form");
                            //console.log(self.get_brochure_pages())
                            //notify_s('Success', 'Your Brochure was successfully saved.');
                        }
                    })
                }else{
                    //console.log(self.get_brochure_pages())
                    //notify_s('Success', 'Your Brochure was successfully saved.');
                    save_workspace_functions("#cBrochure_form");
                }
                
                //notify_s('Success', 'Meron na');
            }
        });
    },

    /*  =====================================
   =====   ====
   ========================================= */
    get_brochure_pages : function(){
        //var declaration
        var json_brochure = [];
        var brochure_page_id = "";var brochure_content = "";

        //collect data in json
        $(".brochure_builder").find(".brochure").each(function(){
            brochure_page_id = $(this).attr("id");
            brochure_content = $(this).html();
            json_brochure.push({
                "id"        :       brochure_page_id,
                "content"   :       brochure_content
            })
        })

        return json_brochure;
    },
    
        /*  =====================================
   =====   ====
   ========================================= */
    object_hover : function(){
        $("body").on("mouseenter",".controls_container",function(){
            var dataID = $(this).attr("data-id");
            $("#cc-controls-" + dataID).removeClass("hide");
            $("#img-properties-" + dataID).removeClass("hide");
            $("#img-properties-act-" + dataID).removeClass("hide");
        });
        
        $("body").on("mouseleave",".controls_container",function(){
            var dataID = $(this).attr("data-id");
            $("#cc-controls-" + dataID).addClass("hide");
            $("#img-properties-" + dataID).addClass("hide");
            $("#img-properties-act-" + dataID).addClass("hide");
        });
    },
    
        /*  =====================================
   =====   ====
   ========================================= */
    clear_page : function(){
        var self = this;
        $("body").on("click",".clearBrochure",function(){
            var page = $(".appendControl").html();
            
            if (page == "") {
                notify_i('Info', 'Your current page is already clear.');
            }else{
                jConfirm( 'Clear Page', 'Are you sure do you want to clear the current page?','', '', '', function(e){
                    if (e == true) {
                        $(".appendControl").html(null)
                        //deactivate onBeforeOnload
                        self.bind_onBeforeOnload(0)
                        notify_s('Success', 'Your current page was successfully clear.');
                    }
                })
            }
            
        });
    },

    blankPage : function(){
        var countPage = $(".brochure").length
        if(countPage==0){
            notify_s('Error', 'Please add brochure page.');
            return false;
        }
    },

    bind_onBeforeOnload : function(status) { // for confirmation on page reload
        if (status == 0) {
            window.onbeforeunload = function() {
                // blank function do nothing
            }
        } else {
            window.onbeforeunload = function(e) {
                return 'You will lose any unsaved edits';
            };
        }
    },
    
    /*  =====================================
    ===== Submit Data from client side to
     server side to store it on the db   ====
    ========================================= */
    save_brochure_db : function(){
        var self = this;
        $("body").on("click",".sBrochureDB",function(){
            
            $(".fRequired").each(function(){
                var fields = $(this).val();
                
                if (fields == "") {
                    $(this).addClass("red_validation");
                }else{
                    $(this).removeClass("red_validation");
                }
            });
            fields_validation(".red_validation","red_validation");
            
            var error_fields = $(".red_validation").length;
            
            if (error_fields == 0) {
                var brochure = {};
            
                brochure['brochure_title'] = $("#bTitle").val();
                brochure['brochure_description'] = $("#bDescription").val();
                brochure['brochure_json'] = self.get_brochure_pages();
                brochure['brochure_page'] = $(".cb_pages_num").val();
                var brochure_json = JSON.stringify(brochure);
                
                console.log(brochure_json);
                
                $.ajax({
                    type : "POST",
                    url  : "/ajax/brochure",
                    data : {action:"save_brochure",brochure_json:brochure_json},
                    success : function(e){
                        var  data_json = JSON.parse(e);
                        //var parse = JSON.parse(data_json['a']);
                        console.log(e)
                        if (data_json['notification'] == "ok") {
                            showNotification({
                                message: data_json['msg'],
                                type: "success",
                                autoClose: true,
                                duration: 3
                            });
                        }
                        
                    }
                })
            }
            
        });
    }
    
}